#include "gameobject.h"
#include "movestate.h"
#include <cmath>

GameObject::GameObject()
    : _simulator(nullptr), _state(nullptr)
{
    setState(new MoveState); // 设置初始状态为移动状态
}

void GameObject::bandSimulator(RVO::RVOSimulator *simulator, int rvoId)
{
    _simulator = simulator;
    _rvoId = rvoId;
}

void GameObject::updateState()
{
    _state->handle(this);

    if (_shouldStop) {
        _simulator->setAgentPrefVelocity(_rvoId, RVO::Vector2(0, 0));
        return;
    }

    RVO::Vector2 goalVector = _target - _position;
    float maxSpeed = _simulator->getAgentMaxSpeed(_rvoId);
    if (RVO::absSq(goalVector) > 10.0f) {
        goalVector = RVO::normalize(goalVector);
    } else {
        goalVector *= 0;
    }
    _simulator->setAgentPrefVelocity(_rvoId, goalVector * maxSpeed);
}

void GameObject::syncFromRVO()
{
    _position = _simulator->getAgentPosition(_rvoId);
}

bool GameObject::isEnemyInRange()
{
    return RVO::abs(_target - _position) <= 60.f;
}

void GameObject::setState(State *state)
{
    if (_state) {
        _state->exit(this);  // 退出旧状态
        delete _state;
    }
    _state = state;
    if (_state) {
        _state->enter(this); // 进入新状态
    }
}

void GameObject::setTarget(const RVO::Vector2 &target)
{
    if(target != RVO::Vector2(0, 0)){
        _target = target;
    }
}

RVO::Vector2 GameObject::getPosition()
{
    return _position;
}

void GameObject::setShouldStop(bool stop)
{
    _shouldStop = stop;
}

bool GameObject::getShouldStop() const
{
    return _shouldStop;
}

void GameObject::setColor(const QColor &color)
{
    _color = color;
}

void GameObject::draw(QPainter *painter)
{
    painter->setPen(_color);
    painter->setBrush(_color);

    painter->save(); // 保存初始状态
    painter->translate(_position.x(), _position.y()); // 移动原点到对象的中心

    RVO::Vector2 vec(_target - _position);            // 获取朝向
    double rad = std::atan2(vec.y(), vec.x());        // 获取旋转弧度
    double deg = rad * 180.0 / M_PI;                  // 获取旋转角度
    painter->rotate(deg);                             // 设置旋转角度（单位：度）

    painter->drawEllipse(QPointF(0, 0), 10, 10);      // 底座
    painter->drawRect(QRectF(QPointF(10, -3),
                             QPointF(18,  3)));       // 炮台
    painter->restore(); // 恢复状态
}
